package com.fmob.client.app.receiver;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.preference.PreferenceManager;
import android.support.v4.app.NotificationCompat;
import android.text.TextUtils;
import android.util.Log;

import com.fmob.client.app.R;
import com.fmob.client.app.application.FMApplication;

import org.json.JSONException;
import org.json.JSONObject;

import cn.jpush.android.api.CmdMessage;
import cn.jpush.android.api.CustomMessage;
import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.JPushMessage;
import cn.jpush.android.api.NotificationMessage;
import cn.jpush.android.service.JPushMessageService;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
import sdk.webview.fmc.com.fmcsdk.activity.H5Activity;
import sdk.webview.fmc.com.fmcsdk.activity.NoticeActivity;
import sdk.webview.fmc.com.fmcsdk.app.AppManager;
import sdk.webview.fmc.com.fmcsdk.base.BaseData;
import sdk.webview.fmc.com.fmcsdk.base.UserApi;
import sdk.webview.fmc.com.fmcsdk.bean.H5UploadImage;
import sdk.webview.fmc.com.fmcsdk.bean.NotificationSound;
import sdk.webview.fmc.com.fmcsdk.bean.NotificationUpdateTaskList;
import sdk.webview.fmc.com.fmcsdk.bean.OpenMessageEvent;
import sdk.webview.fmc.com.fmcsdk.util.Constant;
import sdk.webview.fmc.com.fmcsdk.util.ToastUtils;
import sdk.webview.fmc.com.fmcsdk.util.Url;
import sdk.webview.fmc.com.fmcsdk.util.UserHelper;
import sdk.webview.fmc.com.fmcsdk.util.Utility;
import sdk.webview.fmc.com.fmcsdk.util.XLog;
import sdk.webview.fmc.com.fmcsdk.util.retrofit2.observer.ApiFactory;
import sdk.webview.fmc.com.fmcsdk.util.retrofit2.subscriber.RxBus;

public class PushMessageService extends JPushMessageService {
    private static final String TAG = "PushMessageService";
    private String messageId;//消息ID
    private SharedPreferences defaultSharedPreferences;
    private String messageReceipt = "false";//是否需要回执
    private String messageType;//消息类型
    private String messageTitle;//消息标题
    private Context context;
    private String messageUrl = "";//消息url
    private String messageSubtitle;//消息标题

    Handler handler = new Handler(Looper.getMainLooper());
    private String importance;
    private int language;
    private NotificationCompat.Builder notification;
    private NotificationManager notificationManager;

    @Override
    public void onMessage(Context context, CustomMessage customMessage) {
        this.context = context;
        defaultSharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
        language = defaultSharedPreferences.getInt("lang", 0);
        XLog.i("收到自定义消息" + customMessage);
        String bundle = customMessage.extra;
        //收到自定义消息，向下分发
        processCustomMessage(context, bundle);
        int activitySize = AppManager.getAppManager().getActivitySize();
        if (activitySize != 0) {
            H5UploadImage h5UploadImage = new H5UploadImage();
            h5UploadImage.setUploadImageType(Constant.UPLOAD_MESSAGE_NUMBER);
            RxBus.getDefault().send(h5UploadImage);
        }
    }

    @Override
    public void onNotifyMessageOpened(Context context, NotificationMessage notificationMessage) {
        String nActionExtra = notificationMessage.notificationExtras;
        openMessage(nActionExtra);
    }

    @Override
    public void onMultiActionClicked(Context context, Intent intent) {
        String nActionExtra = intent.getExtras().getString(JPushInterface.EXTRA_NOTIFICATION_ACTION_EXTRA);
        openMessage(nActionExtra);
        //开发者根据不同 Action 携带的 extra 字段来分配不同的动作。
        if (nActionExtra == null) {
            Log.d(TAG, "ACTION_NOTIFICATION_CLICK_ACTION nActionExtra is null");
            return;
        }
        if (nActionExtra.equals("my_extra1")) {
        } else if (nActionExtra.equals("my_extra2")) {
        } else if (nActionExtra.equals("my_extra3")) {
        } else {
        }
    }

    /**
     * 小米通道 在线的情况下 也会走这个方法
     *
     * @param context
     * @param notificationMessage
     */
    @Override
    public void onNotifyMessageArrived(Context context, NotificationMessage notificationMessage) {
        Log.e(TAG, "[onNotifyMessageArrived] " + notificationMessage);
        this.context = context;
        XLog.i("收到通知消息" + notificationMessage);

        String bundle = notificationMessage.notificationExtras;
        Log.v("shuchang", "收到通知消息bundle--->" + bundle);
        RxBus.getDefault().send(new NotificationUpdateTaskList(bundle));

        //处理消息体，播放音频文件
        RxBus.getDefault().send(new NotificationSound(bundle));
    }

    @Override
    public void onNotifyMessageDismiss(Context context, NotificationMessage message) {
        Log.e(TAG, "[onNotifyMessageDismiss] " + message);
    }

    @Override
    public void onRegister(Context context, String registrationId) {
        Log.e(TAG, "[onRegister] " + registrationId);
        Intent intent = new Intent("com.jiguang.demo.message");
        intent.putExtra("rid", registrationId);
        context.sendBroadcast(intent);
    }

    @Override
    public void onConnected(Context context, boolean isConnected) {
        Log.e(TAG, "[onConnected] " + isConnected);
    }

    @Override
    public void onCommandResult(Context context, CmdMessage cmdMessage) {
        Log.e(TAG, "[onCommandResult] " + cmdMessage);
    }

    @Override
    public void onTagOperatorResult(Context context, JPushMessage jPushMessage) {
        TagAliasOperatorHelper.getInstance().onTagOperatorResult(context, jPushMessage);
        super.onTagOperatorResult(context, jPushMessage);
    }

    @Override
    public void onCheckTagOperatorResult(Context context, JPushMessage jPushMessage) {
        TagAliasOperatorHelper.getInstance().onCheckTagOperatorResult(context, jPushMessage);
        super.onCheckTagOperatorResult(context, jPushMessage);
    }

    @Override
    public void onAliasOperatorResult(Context context, JPushMessage jPushMessage) {
        TagAliasOperatorHelper.getInstance().onAliasOperatorResult(context, jPushMessage);
        super.onAliasOperatorResult(context, jPushMessage);
    }

    @Override
    public void onMobileNumberOperatorResult(Context context, JPushMessage jPushMessage) {
        TagAliasOperatorHelper.getInstance().onMobileNumberOperatorResult(context, jPushMessage);
        super.onMobileNumberOperatorResult(context, jPushMessage);
    }

    @Override
    public void onNotificationSettingsCheck(Context context, boolean isOn, int source) {
        super.onNotificationSettingsCheck(context, isOn, source);
        Log.e(TAG, "[onNotificationSettingsCheck] isOn:" + isOn + ",source:" + source);
    }

    private void openMessage(String extras) {


        defaultSharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
        if (!defaultSharedPreferences.getBoolean(Constant.ISLOGIN, false)) {
            XLog.i("ISLOGIN=", context);
            return;
        }


        if (!TextUtils.isEmpty(extras)) {
            try {
                JSONObject json = new JSONObject(extras);
                messageId = json.optString("id");
                messageType = json.optString("type");
                messageTitle = json.optString("title");
                messageSubtitle = json.optString("subTitle");
                String messageTime = json.optString("ts");
                messageReceipt = json.optString("receipt");
                //拼接要跳转的URL
                String url = json.optString("url");
                XLog.i(url);
                if (!TextUtils.isEmpty(url)) {
//                    String[] split = url.split("#");
                    if (url.startsWith("http")) {
//                        messageUrl = split[0] + "?accessToken=" + UserHelper.getToken() + "#" + split[1];
                        if (url.contains("#accessToken#")) {
                            messageUrl = url.replace("#accessToken#", UserHelper.getToken());
                        } else if (url.contains("{accessToken}")) {
                            messageUrl = url.replace("{accessToken}", UserHelper.getToken());
                        }
                    } else {
                        if (url.contains("#accessToken#")) {
                            messageUrl = defaultSharedPreferences.getString(Constant.BASE_ADDRESS_URL, "") + url.replace("#accessToken#", UserHelper.getToken());
                        } else if (url.contains("{accessToken}")) {
                            messageUrl = url.replace("{accessToken}", UserHelper.getToken());
                        }
//                        messageUrl = defaultSharedPreferences.getString(Constant.ADDRESS,"")+"/"+split[0] + "?accessToken=" + UserHelper.getToken() + "#" + split[1];
                    }
                }

                XLog.i("messageUrl=" + messageUrl);
                importance = json.optString("importance");
            } catch (JSONException e) {
                e.printStackTrace();
            }
        } else {
            XLog.i("extras为空");
        }
        //调用消息回执接口
        if (!TextUtils.isEmpty(UserHelper.getToken())) {
            messageReceipt();
        } else {
            XLog.i("token为空");
        }

        //如果消息是先调用心跳接口查看token是否过期，过期的话跳转到登录界面
        sendHeartBeat();
        //直接打开H5界面
        defaultSharedPreferences.edit().putBoolean(Constant.ACTIVITY_IS_EXIST, true).apply();
//        if (!TextUtils.isEmpty(UserHelper.getToken())) {
//
//            if (AppManager.isActivityExist(H5Activity.class)){
//                XLog.i("存在H5Activity=");
////                AppManager.getAppManager().finishActivity(H5Activity.class);
//
//                RxBus.getDefault().send(new OpenMessageEvent(messageUrl));
//            }else {
        Intent intents = new Intent();
        //如果消息url为空跳转到待办任务列表
        XLog.i("messageUrl=" + messageUrl, context);
        if (TextUtils.isEmpty(messageUrl)) {
            String address = defaultSharedPreferences.getString(Constant.BASE_ADDRESS_URL, "") + "/h5/mytask?accessToken=" + UserHelper.getToken() + "#/myMessage";
            intents.putExtra(Constant.H5_URL, address);
        } else {
            intents.putExtra(Constant.H5_URL, messageUrl);
        }
        intents.setClass(context, NoticeActivity.class);
        intents.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intents);
//            }

//        }
    }


    /**
     * 消息已读的接口，点击消息调用
     */
    private void messageRead() {
        ApiFactory.getFactory().create(UserApi.class).sendMessageRead(defaultSharedPreferences.getString(Constant.BASE_ADDRESS_URL, "") + Url.H5_MESSAGE_READ, Url.XMLHTTPREQUEST, UserHelper.getToken(), UserHelper.getUserId(), Long.parseLong(messageId))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<BaseData>() {
                    @Override
                    public void onCompleted() {
                    }

                    @Override
                    public void onError(Throwable e) {
                    }

                    @Override
                    public void onNext(BaseData result) {
                        //如果token过期，重新获取
                        if (result.getStatus().equals(Url.TOKEN_ERROR_STATUS) || result.getStatus().equals(Url.TOKEN_FORBIDDEN)) {
                            XLog.i("点击推送消息token过期");
                            Utility.startLoginActivity(context);
                        }
                    }
                });
    }


    /**
     * 消息回执的接口，接收到消息调用
     */
    private void messageReceipt() {
        ApiFactory.getFactory().create(UserApi.class).sendMessageReceipt(defaultSharedPreferences.getString(Constant.BASE_ADDRESS_URL, "") + Url.H5_MESSAGE_RECEIPT, Url.XMLHTTPREQUEST, UserHelper.getToken(), UserHelper.getUserId(), Long.parseLong(messageId))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<BaseData>() {
                    @Override
                    public void onCompleted() {
                        Log.e("PushReceiver", "messageReceipt result：" + "onCompleted");
                    }

                    @Override
                    public void onError(Throwable e) {
                        Log.e("PushReceiver", "messageReceipt result：" + "onError:" + e);
                    }

                    @Override
                    public void onNext(BaseData result) {
                        Log.e("PushReceiver", "messageReceipt result：" + "onNext:" + result.getMessage() + "---" + result.getStatus());
                        //token过期后自动跳转到登录界面
                        if (result.getStatus().equals(Url.TOKEN_ERROR_STATUS) || result.getStatus().equals(Url.TOKEN_FORBIDDEN)) {
//                            Utility.startLoginActivity(context);
                        }
                    }
                });

    }

    /**
     * 实现自定义推送声音
     *
     * @param context
     */

    private void processCustomMessage(final Context context, String extras) {

        //创建通知栏
        notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        notification = new NotificationCompat.Builder(context);
        //解析自定义消息
//        String extras = bundle.getString(JPushInterface.EXTRA_EXTRA);
        XLog.i("推送消息：" + extras, context);
        if (!TextUtils.isEmpty(extras)) {
            try {
                JSONObject json = new JSONObject(extras);
                messageId = json.optString("id");
                messageType = json.optString("type");
                messageTitle = json.optString("title");
                messageSubtitle = json.optString("subTitle");
                String messageTime = json.optString("ts");
                messageReceipt = json.optString("receipt");
                //拼接要跳转的URL
                String url = json.optString("url");
                XLog.i(url);
                if (!TextUtils.isEmpty(url)) {
//                    String[] split = url.split("#");
                    if (url.startsWith("http")) {
//                        messageUrl = split[0] + "?accessToken=" + UserHelper.getToken() + "#" + split[1];
                        if (url.contains("#accessToken#")) {
                            messageUrl = url.replace("#accessToken#", UserHelper.getToken());
                        } else if (url.contains("{accessToken}")) {
                            messageUrl = url.replace("{accessToken}", UserHelper.getToken());
                        }
                    } else {
                        if (url.contains("#accessToken#")) {
                            messageUrl = defaultSharedPreferences.getString(Constant.BASE_ADDRESS_URL, "") + url.replace("#accessToken#", UserHelper.getToken());
                        } else if (url.contains("{accessToken}")) {
                            messageUrl = url.replace("{accessToken}", UserHelper.getToken());
                        }
//                        messageUrl = defaultSharedPreferences.getString(Constant.ADDRESS,"")+"/"+split[0] + "?accessToken=" + UserHelper.getToken() + "#" + split[1];
                    }
                }

                XLog.i("messageUrl=" + messageUrl);
                importance = json.optString("importance");
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        //调用消息回执接口
        if (!TextUtils.isEmpty(UserHelper.getToken())) {
            messageReceipt();
        }
        //震动提示
        if (defaultSharedPreferences.getBoolean(Constant.VIBRATE, false)) {
            notification.setDefaults(Notification.DEFAULT_VIBRATE);
        }
        if (defaultSharedPreferences.getBoolean(Constant.SOUND, true)) {
            FMApplication.messageSoundCount = 1 + FMApplication.messageSoundCount;
            handler.postDelayed(new Runnable() {
                public void run() {
//                    XLog.i(importance+"importance");
                    if (language == 0) {
                        XLog.i(FMApplication.messageSoundCount + "messageSoundCount");
                        if (FMApplication.messageSoundCount == 1) {
                            if (TextUtils.isEmpty(importance)) {
                                importance = "-1";
                            }
                            //自定义声音
                            if (importance.equals("1")) {
                                notification.setSound(Uri.parse(defaultSharedPreferences.getString(Constant.SOUND_NEW_URL, "android.resource://" + context.getPackageName() + "/" + R.raw.important)));
                            } else {
                                if (messageType.equalsIgnoreCase(context.getString(R.string.message_to_do))) {
                                    notification.setSound(Uri.parse(defaultSharedPreferences.getString(Constant.SOUND_NEW_URL, "android.resource://" + context.getPackageName() + "/" + R.raw.newtask)));
                                } else if (messageType.equalsIgnoreCase(context.getString(R.string.message_grab))) {
                                    notification.setSound(Uri.parse(defaultSharedPreferences.getString(Constant.SOUND_NEW_URL, "android.resource://" + context.getPackageName() + "/" + R.raw.newgrab)));
                                } else if (messageType.equalsIgnoreCase(context.getString(R.string.message_notice))) {
                                    notification.setSound(Uri.parse(defaultSharedPreferences.getString(Constant.SOUND_NEW_URL, "android.resource://" + context.getPackageName() + "/" + R.raw.msgnotify)));
                                } else if (messageType.equalsIgnoreCase(context.getString(R.string.message_expire))) {
                                    notification.setSound(Uri.parse(defaultSharedPreferences.getString(Constant.SOUND_NEW_URL, "android.resource://" + context.getPackageName() + "/" + R.raw.expire)));
                                } else {
                                    notification.setSound(Uri.parse(defaultSharedPreferences.getString(Constant.SOUND_NEW_URL, "android.resource://" + context.getPackageName() + "/" + R.raw.msgnotify)));
                                }
                            }
                            FMApplication.messageSoundCount = 0;
                            startNotification();
                        } else if (FMApplication.messageSoundCount > 1) {
                            notification.setSound(Uri.parse(defaultSharedPreferences.getString(Constant.SOUND_NEW_URL, "android.resource://" + context.getPackageName() + "/" + R.raw.moretask)));
                            FMApplication.messageSoundCount = -100;
                            startNotification();
                        }
                    } else if (language == 2) {
                        if (FMApplication.messageSoundCount == 1) {
                            if (TextUtils.isEmpty(importance)) {
                                importance = "-1";
                            }
                            if (importance.equals("1")) {
                                notification.setSound(Uri.parse(defaultSharedPreferences.getString(Constant.SOUND_NEW_URL, "android.resource://" + context.getPackageName() + "/" + R.raw.important_cht)));
                            } else {
//                                XLog.i("~~--"+messageType);
                                if (messageType.equalsIgnoreCase("待辦")) {
//                                    XLog.i("~~--message_to_do");
//                                    notification.setSound(Uri.parse(defaultSharedPreferences.getString(Constant.SOUND_NEW_URL, "android.resource://" + context.getPackageName() + "/" + R.raw.newtask)));
                                    notification.setSound(Uri.parse(defaultSharedPreferences.getString(Constant.SOUND_NEW_URL, "android.resource://" + context.getPackageName() + "/" + R.raw.newtask_cht)));
                                } else if (messageType.equalsIgnoreCase("搶單")) {
                                    notification.setSound(Uri.parse(defaultSharedPreferences.getString(Constant.SOUND_NEW_URL, "android.resource://" + context.getPackageName() + "/" + R.raw.newgrab_cht)));
                                } else if (messageType.equalsIgnoreCase(context.getString(R.string.message_notice))) {
                                    notification.setSound(Uri.parse(defaultSharedPreferences.getString(Constant.SOUND_NEW_URL, "android.resource://" + context.getPackageName() + "/" + R.raw.msgnotify)));
                                } else if (messageType.equalsIgnoreCase(context.getString(R.string.message_expire))) {
                                    notification.setSound(Uri.parse(defaultSharedPreferences.getString(Constant.SOUND_NEW_URL, "android.resource://" + context.getPackageName() + "/" + R.raw.expire_cht)));
                                } else {
//                                    XLog.i("~~--其他");
                                    notification.setSound(Uri.parse(defaultSharedPreferences.getString(Constant.SOUND_NEW_URL, "android.resource://" + context.getPackageName() + "/" + R.raw.msgnotify)));
                                }

                            }
                            FMApplication.messageSoundCount = 0;
                            startNotification();
                        } else if (FMApplication.messageSoundCount > 1) {
                            XLog.i(importance + "多个");
                            notification.setSound(Uri.parse(defaultSharedPreferences.getString(Constant.SOUND_NEW_URL, "android.resource://" + context.getPackageName() + "/" + R.raw.moretask_cht)));
                            FMApplication.messageSoundCount = -100;
                            startNotification();
                        }
                    } else {
                        if (FMApplication.messageSoundCount == 1) {
                            if (TextUtils.isEmpty(importance)) {
                                importance = "-1";
                            }
                            //自定义声音
                            notification.setSound(Uri.parse(defaultSharedPreferences.getString(Constant.SOUND_NEW_URL, "android.resource://" + context.getPackageName() + "/" + R.raw.msgnotify)));
                            FMApplication.messageSoundCount = 0;
                            startNotification();
                        } else if (FMApplication.messageSoundCount > 1) {
                            notification.setSound(Uri.parse(defaultSharedPreferences.getString(Constant.SOUND_NEW_URL, "android.resource://" + context.getPackageName() + "/" + R.raw.msgnotify)));
                            FMApplication.messageSoundCount = -100;
                            startNotification();
                        }
                    }
                }
            }, 1000);
            handler.postDelayed(new Runnable() {
                public void run() {
                    FMApplication.messageSoundCount = 0;
                }
            }, 10000);
        } else {
            startNotification();
        }

        //如果消息是先调用心跳接口查看token是否过期，过期的话跳转到登录界面
        sendHeartBeat();
    }

    private void startNotification() {
        XLog.i("创建通知栏");
        int i = 1;
        //创建通知栏，点击通知栏时发送广播
        Intent intentClick = new Intent(context, NotificationBroadcastReceiver.class);
        intentClick.setAction("notification_clicked");
        intentClick.putExtra("messageId", messageId);
        intentClick.putExtra("messageReceipt", messageReceipt);
        intentClick.putExtra("messageUrl", messageUrl);
        PendingIntent pendingIntentClick = PendingIntent.getBroadcast(context.getApplicationContext(), ++i, intentClick, PendingIntent.FLAG_CANCEL_CURRENT);
        notification.setAutoCancel(true)
                .setContentText(messageTitle)
                .setContentTitle(messageType)
                .setContentIntent(pendingIntentClick)
                .setSmallIcon(R.mipmap.icon);
        notificationManager.notify(1, notification.build());
    }

    /**
     * 发送心跳接口
     */
    private void sendHeartBeat() {
        ApiFactory.getFactory().create(UserApi.class).sendHeartBeat(defaultSharedPreferences.getString(Constant.BASE_ADDRESS_URL, "") + Url.SEND_HEARTBEAT, Url.XMLHTTPREQUEST, UserHelper.getToken())

                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<BaseData>() {
                    @Override
                    public void onCompleted() {
                    }

                    @Override
                    public void onError(Throwable e) {
                    }

                    @Override
                    public void onNext(BaseData result) {//成功后向后台发送GPS数据
                        if (result.getStatus().equals(Url.TOKEN_ERROR_STATUS) || result.getStatus().equals(Url.TOKEN_FORBIDDEN)) {
                            XLog.i("推送消息token过期");
                            Utility.startLoginActivity(context);
                        }

                    }
                });
    }
}
